package com.boarsoft.boar.gateway.web;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.proxy.AsyncProxyServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.boarsoft.common.Util;

/**
 * 
 * 
 * @author Mac_J
 *
 */
public class GatewayHttpServlet3 extends AsyncProxyServlet {
	private static final long serialVersionUID = -4634847690862338373L;
	private static final Logger log = LoggerFactory.getLogger(GatewayHttpServlet3.class);

	private final static Properties prop = new Properties();

	static {
		try {
			log.info("Load testing.properties ...");
			prop.load(GatewayHttpServlet3.class.getClassLoader().getResourceAsStream("conf/testing.properties"));
		} catch (IOException e) {
			log.error("Error on load config.properties.", e);
		}
	}

	@Override
	public void service(final HttpServletRequest req, final HttpServletResponse rsp) throws ServletException, IOException {
		Enumeration<String> hn = req.getHeaderNames();
		while (hn.hasMoreElements()) {
			String n = hn.nextElement();
			System.out.print(n);
		}
		System.out.println(req.getHeader("User-Agent"));
		// 从请求头中提取上下文和App版本号
		String cp = req.getPathInfo();
		cp = cp.substring(0, cp.substring(1).indexOf("/") + 1);
		String cv = req.getHeader("client-version");
		String sa = prop.getProperty(String.format("%s|%s", cp, cv)); // 获取Web应用服务器地址
		if (Util.strIsEmpty(sa)) {
			rsp.sendError(HttpStatus.SERVICE_UNAVAILABLE_503);
			return;
		}
		// 替换原请求中的域名为实际提供服务的应用地址
		StringBuffer sb = req.getRequestURL();
		// http://xxx/.... 替换xxx部份
		int i = sb.substring(7).indexOf("/") + 7;
		String url = sb.replace(7, i, sa).toString();
		log.debug("rewrite {} to {}", sb.toString(), url);
		req.setAttribute("rewriteUrl", url);
		try {
			super.service(req, rsp);
		} catch (Exception e) {
			// TODO 只捕获特定的异常
			log.error("Error on rewrite url {} to {}", sb.toString(), url, e);
			rsp.sendError(HttpStatus.BAD_GATEWAY_502);
		}
		return;
	}

	@Override
	public String rewriteTarget(HttpServletRequest req) {
		return (String) req.getAttribute("rewriteUrl");
	}
}
